import 'dart:core';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:kasax/commons/commons.dart';
import 'package:kasax_demos2/entry/entrys.dart';
import 'package:kasax_demos2/widgets/posts_widgets.dart';

/// Scaffold 可视化空间，我们一般将Sliver放在CustomScrollView的slivers中
/// GridView == CustomScrollView(slivers:SliverGrid())
class SliverDemoHome2 extends StatefulWidget {
  const SliverDemoHome2({Key? key}) : super(key: key);

  @override
  _SliverDemoHome2State createState() => _SliverDemoHome2State();
}

// SliverGridDelegateWithFixedCrossAxisCount设置交叉轴上的条目的数量
class _SliverDemoHome2State extends State<SliverDemoHome2> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return PostsListWidget((BuildContext context, AsyncSnapshot<List<Posts>> snapshot) {
      log("PostsListWidget buildPageContent run...");
      return buildCustomScrollView(snapshot);
    });
  }

  buildPageContent(AsyncSnapshot<List<Posts>> asyncsnapshot) {
    var connectionState = asyncsnapshot.connectionState;
    log("connectionState: $connectionState");
    if (connectionState == ConnectionState.waiting) {
      return buildLoadingWidget();
    } else if (connectionState == ConnectionState.done) {
      return (asyncsnapshot.data == null || asyncsnapshot.data!.isEmpty)
          ? buildLoadingWidget()
          : buildCustomScrollView(asyncsnapshot);
    }
  }

  CustomScrollView buildCustomScrollView(AsyncSnapshot<List<Posts>> asyncsnapshot) {
    return CustomScrollView(
      slivers: [
        // 显示在安全区域
        SliverSafeArea(
            // 添加内边距
            sliver: SliverPadding(
          padding: EdgeInsets.all(8.0),
          sliver: SliverGridDemo(asyncsnapshot.data!),
        ))
      ],
    );
  }
}

class SliverGridDemo extends StatelessWidget {
  final List<Posts> posts;

  const SliverGridDemo(this.posts, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return sliverGrid();
  }

  testData() {
    posts == null || posts.isEmpty ? buildLoadingWidget() : sliverGrid();
  }

  SliverGrid sliverGrid() {
    return SliverGrid(
      delegate: SliverChildBuilderDelegate((context, index) {
        return Container(
          child: Image.network(
            posts[index].imageUrl,
            fit: BoxFit.cover,
          ),
        );
      }, childCount: posts.length),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, crossAxisSpacing: 8.0, mainAxisSpacing: 8.0, childAspectRatio: 1.6),
    );
  }
}
